import axios, { AxiosRequestConfig, AxiosRequestHeaders } from 'axios'
import ProjectConfig from '@/settings/projectSetting'
import {
  getToken
} from '@/utils/auth'

import Cookies from 'js-cookie'
import router from '@/router'
import { ElNotification } from 'element-plus'
import store from '@/store'

// 创建实例时设置配置的默认值
const instance = axios.create({
  baseURL: import.meta.env.NODE_ENV === 'production' ? import.meta.env.VITE_GLOB_API_URL : '/', // .env.development 的 base_url
  timeout: ProjectConfig.timeout,
})

// 覆写库的超时默认值
// 现在，在超时前，所有请求都会等待 2.5 秒
// instance.defaults.timeout = 2500

// 添加请求拦截器
instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const headers: AxiosRequestHeaders = {
      'Content-Type': 'application/json',
      'Authorization': ''
    }
    if (getToken()) {
      // 让每个请求携带自定义token 请根据实际情况自行修改
      headers['Authorization'] = 'Bearer ' + getToken()
    }
    config.headers = headers
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(response => {
  if (response.status !== 200) {
    return Promise.reject(new Error(response.data || 'Error'))
  }
  return response.data
},
  // 错误处理
  (error) => {
    // 兼容blob下载出错json提示
    if (error.response.data instanceof Blob &&
      error.response.data.type.toLowerCase().indexOf('json') !== -1) {
      const reader = new FileReader()
      reader.readAsText(error.response.data, 'utf-8')
      reader.onload = function () {
        const errorMsg = JSON.parse(!reader.result ? reader.result! : '').message
        ElNotification({
          message: errorMsg,
          type: 'error',
          duration: 5000
        })
      }
    } else {
      let code:number = 0
      let point_message:string = ''
      code = error.response.data.code
      point_message = error.response.data.message
      try {
        console.log(code)
        console.log(point_message)
      } catch (e) {
        if (error.toString().indexOf('Error:timeout') !== -1) {
          ElNotification({
            message: '网络请求超时',
            type: 'error',
            duration: 5000
          })
          return Promise.reject(error)
        }
      }
      if (code) {
        if (code === 401) {
          ElNotification({
            message: point_message ? point_message : '系统请求验证错误',
            type: 'error',
            duration: 5000
          })
          // store.dispatch('logout').then(() => {
          //   Cookies.set('point', String(code))
          //   Cookies.set('point_message', point_message)
          //   router.push({path:'/login'}).catch(() => {})
          // })
        } else if (code === 403) {
          router.push({
            path: '/401'
          }).catch(() => {})
        } else if (code === 404) {
          router.push({
            path: '/404'
          }).catch(() => {})
        } else {
          ElNotification({
            message: point_message ? point_message : '系统异常,请联系系统管理员',
            type: 'error',
            duration: 5000
          })
        }
      } else {
        ElNotification({
          message: point_message ? point_message : '后台服务请求失败,请联系系统管理员',
          type: 'error',
          duration: 5000
        })
      }
    }
    return Promise.reject(error)
  })

export default instance